package com.itaming.lycheeframework.support.cipher;

import com.itaming.lycheeframework.support.utils.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 加密器工厂类
 *
 * @author A.Ming
 */

public class EncryptorFactory {

    /**
     * 加密器列表
     */
    private static final Map<CipherAlgorithm, Encryptor<?>> encryptors = new HashMap<>();

    /**
     * 注册加密器
     *
     * @param algorithm 键
     * @param encryptor 加密器
     */
    public static void register(CipherAlgorithm algorithm, Encryptor<?> encryptor) {
        if (algorithm != null && encryptor != null) {
            encryptors.put(algorithm, encryptor);
        }
    }

    /**
     * 获取加密器
     *
     * @param algorithm 加密算法
     * @return 加密器
     */
    public static Encryptor<?> getEncryptor(CipherAlgorithm algorithm) {
        return algorithm == null ? null : encryptors.get(algorithm);
    }

    static {
        // 注册加密器
        for (CipherAlgorithm cipherAlgorithm : CipherAlgorithm.values()) {
            if (!encryptors.containsKey(cipherAlgorithm)) {
                register(cipherAlgorithm, ReflectionUtil.newInstance(cipherAlgorithm.getEncryptorClass()));
            }
        }
    }

}
